<template>
  <div style="margin-top: 10px" class="app-contain">
    <el-row :gutter="50">
      <el-col :span="7">
        <el-card>
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <el-row style="text-align: center">
            <el-upload action="/api/student/upload/image"  accept=".jpg,.png" :show-file-list="false"  :on-success="uploadSuccess">
              <el-avatar class="el-dropdown-avatar" :size="100" :src="form.imagePath === null ? require('@/assets/avatar.png') : form.imagePath"></el-avatar>
            </el-upload>
          </el-row>
          <el-row class="user-info-userName">
            <label>{{form.userName}}</label>
          </el-row>
          <el-divider/>
          <el-row class="user-info-fullInfo">
            <label>姓名：{{form.realName}}</label><br/>
            <!-- <label>年级：{{levelFormatter(form.userLevel)}}</label><br/> -->
            <label>注册时间：{{form.createTime}}</label><br/>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="17">
        <el-card shadow="hover">
          <el-tabs active-name="event" type="card">
            <!-- <el-tab-pane label="用户动态" name="event">
              <div class="block">
                <el-timeline>
                  <el-timeline-item  :timestamp="item.createTime" placement="top" :key="item.id" v-for="item in event">
                    <el-card>
                      <p>{{item.content}}</p>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane> -->
            <el-tab-pane label="个人资料修改" name="update">
              <el-form :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules">
                <el-form-item label="真实姓名：" prop="realName" required>
                  <el-input v-model="form.realName"></el-input>
                </el-form-item>
                <!-- <el-form-item label="年龄：">
                  <el-input v-model="form.age"></el-input>
                </el-form-item> -->
                <el-form-item label="性别：">
                  <el-select v-model="form.sex" placeholder="性别" clearable>
                    <el-option v-for="item in sexEnum" :key="item.key" :value="item.key"
                               :label="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="出生日期：" class="fixed-width-form-item">
                  <el-date-picker v-model="form.birthDay" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"/>
                </el-form-item>
                <el-form-item label="MBTI：" class="fixed-width-form-item">
                  <el-input v-model="form.mbti" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱："  required prop="email">
                  <el-input v-model="form.email" type="email"></el-input>
                </el-form-item>
                <el-form-item label="手机号：" required  prop="phone">
                  <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <!-- <el-form-item label="年级：" prop="userLevel" required>
                  <el-select v-model="form.userLevel" placeholder="年级">
                    <el-option v-for="item in levelEnum" :key="item.key" :value="item.key"
                               :label="item.value"></el-option>
                  </el-select>
                </el-form-item> -->
                <el-form-item>
                  <el-button type="primary" @click="submitForm">更新</el-button>
                  <el-button type="success" @click="addMBTI">更新MBTI结果</el-button>
                  <el-button type="info" @click="uploadResume">上传简历</el-button>
                  <el-button type="warning" @click="viewResume">查看简历</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="mbtiModalVisible" title="更新MBTI结果">
      <el-form>
        <el-form-item label="选择测试题：">
          <el-row>
            <el-col :span="18">
              <el-select v-model="mbti" placeholder="请选择">
                <el-option v-for="task in tasks" :key="task.id" :label="task.title" :value="task.id"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mbtiModalVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMBTI">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import userApi from '@/api/user'
import dashboardApi from '@/api/dashboard'
import examPaperAnswerApi from '@/api/examPaperAnswer'
import { mapGetters, mapState } from 'vuex'

export default {
  data () {
    return {
      event: [],
      form: {
        userName: '',
        realName: '',
        age: '',
        sex: '',
        email: '',
        birthDay: null,
        phone: null,
        userLevel: null,
        createTime: null,
        imagePath: null
      },
      resumeURL: 'resume/',
      formLoading: false,
      rules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: function (rule, value, callback) {
              if (
                /^\w{1,64}@[ a-z0-9\- ]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(value) === false
              ) {
                callback(new Error('请输入正确的邮箱'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) === false) {
                callback(new Error('手机号格式错误'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      mbtiModalVisible: false,
      mbti: '',
      tasks: [],
      mbtiCharacter: '',
      mbtiAnaly: '',
      mbtiDisplay: '',
      biographicalNotes: ''
    }
  },
  created () {
    let _this = this
    userApi.getUserEvent().then(re => {
      _this.event = re.response
    })
    userApi.getCurrentUser().then(re => {
      _this.form = re.response
    })
    // Fetch tasks and filter by status
    dashboardApi.task().then(response => {
      if (response.code === 1) {
        _this.tasks = response.response.filter(task => task.status === 3)
      }
    })
  },
  methods: {
    uploadSuccess (re, file) {
      if (re.code === 1) {
        window.location.reload()
      } else {
        this.$message.error(re.message)
      }
    },
    submitForm() {
      let _this = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true;
          userApi.update(this.form).then(data => {  // Send the form data directly
            if (data.code === 1) {
              _this.$message.success(data.message);
            } else {
              _this.$message.error(data.message);
            }
            _this.formLoading = false;
          }).catch(e => {
            _this.formLoading = false;
            _this.$message.error('更新失败: ' + e.message);
          });
        } else {
          return false;
        }
      });
    },
    levelFormatter (level) {
      return this.enumFormat(this.levelEnum, level)
    },
    addMBTI() {
      this.mbtiModalVisible = true;
    },
    saveMBTI() {
      if (!this.mbti) {
        this.$message.error('请选择一个有效的测试题');
        return;
      }
      this.formLoading = true;
      examPaperAnswerApi.read(this.mbti).then(response => {
        if (response.code === 1) {
          this.form.mbti = response.response.mbtl;
          this.mbtiDisplay = response.response.mbtl;
          this.$message.success('MBTI结果更新成功');
        } else {
          this.$message.error('获取MBTI结果失败: ' + response.message);
        }
        this.mbtiModalVisible = false;
        this.formLoading = false;
      }).catch(error => {
        this.$message.error('请求失败: ' + error);
        this.formLoading = false;
      });
    },
    uploadResume() {
      let fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = 'image/*,application/pdf';  // Accept image files and PDF
      fileInput.onchange = e => {
        let file = e.target.files[0];
        // Check if the file size is greater than 30MB
        if (file.size > 30 * 1024 * 1024) {
          this.$message.error('文件大小超过30MB限制，请选择较小的文件。');
          return;
        }
        let reader = new FileReader();
        reader.readAsDataURL(file);  // Continue to read file as Base64
        reader.onload = () => {
          this.biographicalNotes = reader.result;  // Store the Base64 string
          userApi.upload({ biographicalNotes: this.biographicalNotes }).then(response => {
            this.$message.success('简历上传成功');
          }).catch(error => {
            this.$message.error('上传失败: ' + error.message);
          });
        };
        fileInput.click();
      }
      document.body.appendChild(fileInput);  // Add to body to ensure visibility
      fileInput.click();
      document.body.removeChild(fileInput);  // Clean up
    },
    viewResume() {
      userApi.getResume().then(response => {
        if (response.response) {
          const fullPath = this.resumeURL + response.response;
          window.open(fullPath, '_blank');
        } else {
          this.$message.error('无法获取简历数据');
        }
      }).catch(error => {
        this.$message.error('获取简历失败: ' + error.message);
      });
    }
  },
  computed: {
    ...mapGetters('enumItem', [
      'enumFormat'
    ]),
    ...mapState('enumItem', {
      sexEnum: state => state.user.sexEnum,
      levelEnum: state => state.user.levelEnum
    })
  }
}
</script>

<style lang="scss" scoped>
.fixed-width-form-item {
  width: 300px; // Adjust this width as needed to match the design
}
</style>
